import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:riverpod_t/base/base_consumer_widget.dart';
import 'package:riverpod_t/base/base_grid_view.dart';
import 'package:riverpod_t/base/base_stateful_page.dart';
import 'package:riverpod_t/base/empty_widget.dart';
import 'package:riverpod_t/page/home/river/home_list_river.dart';
import 'package:riverpod_t/page/home/router/home_router.dart';
import 'package:riverpod_t/page/home/state/home_state.dart';
import 'package:riverpod_t/page/home/widget/car_toon_widget.dart';
import 'package:riverpod_t/until/app_util.dart';

class HomePage extends BasePage {
  const HomePage({super.key});

  @override
  BasePageState<BasePage> getState() => _HomePageState();
}

class _HomePageState extends BasePageState<HomePage> {
  /// 列表控制器
  final ScrollController scrollController = ScrollController();

  /// 刷新组建控制器
  final RefreshController refreshController = RefreshController(initialRefresh: false);

  @override
  void initState() {
    super.initState();
    super.appBarTitle = '列表一';
    allowBackNavigation = false;
  }

  @override
  Widget buildLeftButton() {
    return const SizedBox();
  }

  Widget _listBody(BuildContext context, HomeState state, WidgetRef ref) {
    if (AppUtil.isEmpty(state.list)) return EmptyWidget();
    return BaseGridView(
      enablePullDown: true,
      enablePullUp: true,
      onRefresh: () => ref.read(homeListRiverProvider.notifier).refresh(isRefresh: true),
      onLoading: () => ref.read(homeListRiverProvider.notifier).refresh(),
      refreshController: refreshController,
      scrollController: scrollController,
      data: state.list,
      padding: EdgeInsets.all(10.h),
      childAspectRatio: 0.7,
      crossAxisSpacing: 10.w,
      mainAxisSpacing: 10.h,
      crossAxisCount: 2,
      backgroundColor: const Color(0xFFF3F4F8),
      itemBuilder: (context22, index) {
        return CarTonWidget(
          index: index,
          model: state.list[index],
          onTap: () {
            HomeNavigator.toHomeDetailPage(context, imageUrl: state.list[index].image ?? '');
          },
        );
      },
    );
  }

  void _listenOpChange(AsyncValue<HomeState?>? previous, AsyncValue<HomeState?> next) {
    refreshController.refreshCompleted();
    refreshController.loadComplete();
    if (next.value?.hasNext == false) {
      refreshController.loadNoData();
    }
  }

  @override
  Widget buildPage(BuildContext context) {
    return BaseConsumerWidget<HomeState>(
      provider: homeListRiverProvider,
      // 构建UI
      builder: (context, state, ref) => _listBody(context, state, ref),
      // 监听数据变化
      listenStateChange: (context, p, n) => _listenOpChange(p, n),
    );
  }
}
